from datetime import datetime
from flask import Blueprint, jsonify, request
from web.services.market_data_service import MarketDataService

udf_bp = Blueprint('udf', __name__, url_prefix='/api/udf')
market_service = MarketDataService()

@udf_bp.route('/config')
def get_config():
    """UDF配置接口"""
    return jsonify({
        "supported_resolutions": ['1', '5', '15', '30', '60','1D', '1W', '1M'],
        "supports_group_request": False,
        "supports_marks": False,
        "supports_search": True,
        "supports_timescale_marks": False,
        "supports_time": True
    })

@udf_bp.route('/symbols', methods=['GET'])
def get_symbols():
    """商品信息接口"""
    symbol = request.args.get('symbol')
    
    symbol_info = market_service.get_symbol_info(symbol)
    if symbol_info:
        return jsonify(symbol_info)
    else:
        return jsonify({
            "s": "error",
            "errmsg": "Symbol not found"
        })

@udf_bp.route('/quotes', methods=['GET'])
def get_quotes():
    """实时行情接口"""
    try:
        symbol = request.args.get('symbols') # 只取第一个股票
        if not symbol:
            return jsonify([])
            
        quote_data = market_service.get_stock_quote(symbol)
        return jsonify([quote_data])
        
    except Exception as e:
        return jsonify([{"s": "error", "errmsg": str(e)}])

@udf_bp.route('/history', methods=['GET'])
def get_history():
    """K线数据接口"""
    try:
        symbol = request.args.get('symbol', '')
        interval = request.args.get('resolution', '')
        from_ts = int(request.args.get('from', 0))
        to_ts = int(request.args.get('to', 0)) or int(datetime.now().replace(hour=23, minute=59, second=59).timestamp())
        
        if not all([symbol, interval, from_ts, to_ts]):
            return jsonify({
                "s": "error",
                "errmsg": "Missing required parameters"
            })
            
        history_data = market_service.get_kline_data(symbol, interval, from_ts, to_ts)
        return jsonify(history_data)
        
    except Exception as e:
        return jsonify({
            "s": "error",
            "errmsg": str(e)
        }), 400

@udf_bp.route('/time')
def get_time():
    """服务器时间接口"""
    return jsonify(int(datetime.now().timestamp())) 

@udf_bp.route('/search')
def search():
    """搜索股票"""
    query = request.args.get('query', '')
    limit = int(request.args.get('limit', 30))
    
    results = market_service.search_stocks(query, limit)
    return jsonify(results) 
